package com.easy.redis.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("redis")
@CrossOrigin
public class RedisController {
    @Autowired
    RedisTemplate redisTemplate;
@RequestMapping(value = "setval",method = RequestMethod.POST)
    public void setVal(String key,String val){
        redisTemplate.opsForValue().set(key,val);
    }

    @RequestMapping(value = "getval",method = RequestMethod.GET)
    public String getVal(String key){
        return redisTemplate.opsForValue().get(key)+"";
    }
    @RequestMapping(value = "deleteval",method = RequestMethod.DELETE)
    public Object deleteVal(String key){
       return redisTemplate.opsForValue().getAndDelete(key);
    }


    @RequestMapping(value = "setvalexpire",method = RequestMethod.POST)
    public void setValExpire(String key,String val,int time,String unit){
        TimeUnit tu=null;
        if("S".equalsIgnoreCase(unit)){
            tu=TimeUnit.SECONDS;
        }else if("M".equalsIgnoreCase(unit)){
            tu=TimeUnit.MINUTES;
        }else{
            tu=TimeUnit.SECONDS;
        }
        redisTemplate.opsForValue().set(key,val,time,tu);
    }




}
